/*
 * VsMotionDetector.cpp
 *
 *  Created on: Mar 28, 2013
 *      Author: andre
 */

#include "VsMotionDetector.h"

VsMotionDetector::VsMotionDetector(VsMotionConfig *config)
{
	int i=0;
	this->config = config;

	CvSize size = cvSize(config->res.width,config->res.height);

	for(i=0;i<this->config->numberOfBackGrounds;i++)
	{
		this->grayBackgroundsImgs.push_back(cvCreateImage(size,IPL_DEPTH_8U,1));
		this->colorBackgroundsImgs.push_back(cvCreateImage(size,IPL_DEPTH_8U,3));

		cvZero(grayBackgroundsImgs[i]);
		cvZero(colorBackgroundsImgs[i]);
	}

	this->foregroundImg = cvCreateImage(size,IPL_DEPTH_8U,1);
	this->grayImg = cvCreateImage(size,IPL_DEPTH_8U,1);
}

VsMotionDetector::~VsMotionDetector()
{
	int i;

	for(i=0;i<(int)grayBackgroundsImgs.size();i++)
		if(grayBackgroundsImgs[i])
			cvReleaseImage(&grayBackgroundsImgs[i]);

	for(i=0;i<(int)colorBackgroundsImgs.size();i++)
		if(colorBackgroundsImgs[i])
			cvReleaseImage(&colorBackgroundsImgs[i]);

	if(foregroundImg)
		cvReleaseImage(&foregroundImg);

	if(grayImg)
		cvReleaseImage(&grayImg);

	grayBackgroundsImgs.clear();
	colorBackgroundsImgs.clear();

	printf("Deletei MotionDetector\n");
}

int VsMotionDetector::process(IplImage *inputImg)
{
	static int i;

	cvPyrDown(inputImg, grayImg, CV_GAUSSIAN_5x5);

	cvAbsDiff(grayImg,grayBackgroundsImgs[0],foregroundImg);

	cvThreshold(foregroundImg,foregroundImg,config->threshold,255,CV_THRESH_BINARY);

	for(i=1;i<config->numberOfBackGrounds;i++)
		cvCopy(grayBackgroundsImgs[i],grayBackgroundsImgs[i-1]);

	cvCopy(grayImg,grayBackgroundsImgs[config->numberOfBackGrounds-1]);

	return 0;
}
